//! Tests for time utility functions

use unitree_ros2_rs::utils::time_utils::*;
use chrono::Datelike;

#[test]
fn test_timespec_to_datetime() {
    // Create a mock TimeSpec for testing
    let mut timespec = r2r::unitree_go::msg::TimeSpec::default();
    timespec.sec = 1640995200; // 2022-01-01 00:00:00 UTC
    timespec.nanosec = 500000000; // 0.5 seconds
    
    let result = timespec_to_datetime(&timespec);
    assert!(result.contains("2022-01-01"));
    assert!(result.contains("00:00:00.500"));
    assert!(result.contains("UTC"));
}

#[test]
fn test_invalid_timespec() {
    let mut timespec = r2r::unitree_go::msg::TimeSpec::default();
    timespec.sec = -1; // Invalid timestamp
    timespec.nanosec = 0;
    
    let result = timespec_to_datetime(&timespec);
    // DateTime::from_timestamp(-1, 0) actually returns Some(1969-12-31 23:59:59 UTC)
    // So we need to test with a truly invalid timestamp
    println!("Result for sec=-1: {}", result);
    
    // Test with an extremely large invalid nanosecond value
    timespec.sec = 0;
    timespec.nanosec = 2_000_000_000; // > 1 billion nanoseconds (invalid)
    let result2 = timespec_to_datetime(&timespec);
    assert!(result2.contains("Invalid timestamp"));
}

#[test]
fn test_timespec_to_datetime_utc() {
    let mut timespec = r2r::unitree_go::msg::TimeSpec::default();
    timespec.sec = 1640995200;
    timespec.nanosec = 0;
    
    let result = timespec_to_datetime_utc(&timespec);
    assert!(result.is_some());
    
    let dt = result.unwrap();
    assert_eq!(dt.year(), 2022);
    assert_eq!(dt.month(), 1);
    assert_eq!(dt.day(), 1);
}

#[test]
fn test_current_utc_string() {
    let result = current_utc_string();
    assert!(result.contains("UTC"));
    assert!(result.len() > 20); // Should be a reasonable length
}

#[test]
fn test_timespec_diff_ms() {
    let mut stamp1 = r2r::unitree_go::msg::TimeSpec::default();
    stamp1.sec = 1640995201; // 1 second later
    stamp1.nanosec = 0;
    
    let mut stamp2 = r2r::unitree_go::msg::TimeSpec::default();
    stamp2.sec = 1640995200;
    stamp2.nanosec = 0;
    
    let diff = timespec_diff_ms(&stamp1, &stamp2);
    assert_eq!(diff, Some(1000)); // 1 second = 1000ms
}